package com.heima.search.listen;

import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.feigns.ArticleFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.search.service.ArticleSearchService;
import com.heima.search.vo.SearchArticleVO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description:
 * @Version: V1.0
 */
@Component
@Slf4j
public class ArticleAddOrRemoveListener {

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    ArticleSearchService articleSearchService;

    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void addArticle(@Payload String articleId, Message message, Channel channel){
        log.info("搜索微服务 接收到添加文章到索引库消息==> {}", articleId);

        try {
            //1 根据id查询文章
            ResponseResult<ApArticle> result = articleFeign.findArticle(Long.valueOf(articleId));
            if (result.getCode() != 0) {
                log.info("远程调用失败   findArticle: {}",articleId);
                return;
            }
            ApArticle apArticle = result.getData();
            if (apArticle != null) {
                //2 执行保存索引库
                SearchArticleVO searchArticleVO = new SearchArticleVO();
                BeanUtils.copyProperties(apArticle, searchArticleVO);
                searchArticleVO.setLayout(apArticle.getLayout().intValue());
                articleSearchService.saveArticle(searchArticleVO);
            }

            //3 手动提交mq
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("成功更新索引信息   add: {}",articleId);
    }

    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void removeArticle(@Payload String articleId, Message message, Channel channel){
        log.info("搜索微服务 接收到删除索引库文章消息==> {}",articleId);
        try {
            articleSearchService.deleteArticle(articleId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("成功更新索引信息   delete: {}",articleId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}",articleId,e.getMessage());
        }
    }

}